package com.ruoyi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HouseSaleStatus;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.Broker;
import com.ruoyi.common.dto.HouseListRespDTO;
import com.ruoyi.common.dto.HouseQueryReqDTO;
import com.ruoyi.common.enums.HouseType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.SnowFlake;
import com.ruoyi.domain.OfficeBuilding;
import com.ruoyi.domain.Region;
import com.ruoyi.domain.ShopCharacteristics;
import com.ruoyi.domain.ShopFacilities;
import com.ruoyi.domain.dto.req.ShopInsertReqDTO;
import com.ruoyi.houses.domain.Houses;
import com.ruoyi.houses.mapper.HousesMapper;
import com.ruoyi.mapper.BrokerMapper;
import com.ruoyi.mapper.OfficeBuildingMapper;
import com.ruoyi.mapper.RegionMapper;
import com.ruoyi.service.ImageService;
import com.ruoyi.service.OfficeBuildingService;
import com.ruoyi.service.ShopCharacteristicsService;
import com.ruoyi.service.ShopFacilitiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author 25088
 * @description 针对表【office_building(商业办公表)】的数据库操作Service实现
 * @createDate 2024-09-14 15:39:15
 */
@Service
public class OfficeBuildingServiceImpl extends ServiceImpl<OfficeBuildingMapper, OfficeBuilding>
        implements OfficeBuildingService {
    @Autowired
    private HousesMapper housesMapper;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private BrokerMapper brokerMapper;
    @Autowired
    private ShopCharacteristicsService shopCharacteristicsService;
    @Autowired
    private ShopFacilitiesService shopFacilitiesService;
    @Autowired
    private ImageService imageService;

    @Override
    @Transactional//开启本地事务
    public R insertOfficeBuilding(ShopInsertReqDTO shopInsertReqDTO) {
        //雪花算法生成id
        SnowFlake snowFlake = new SnowFlake(1, 1);
        long houseId = snowFlake.nextId();
        //复制房屋实体类
        Houses houses = new Houses();
        BeanUtil.copyProperties(shopInsertReqDTO, houses);
        //房源id
        houses.setId(houseId);
        //设置房屋状态为待售
        houses.setSaleStatus(HouseSaleStatus.FORSALE.getStatus());
        Long cityId1 = shopInsertReqDTO.getCityIds()[0];
        houses.setProvinceId(cityId1);
        Long cityId = shopInsertReqDTO.getCityIds()[1];
        Region city = regionMapper.selectById(cityId);
        houses.setCityId(cityId);
        houses.setCityName(city.getName());
        //区域id
        Long districtId = shopInsertReqDTO.getCityIds()[2];
        houses.setDistrictId(districtId);
        //查询区域名称
        Region region = regionMapper.selectById(districtId);
        houses.setDistrictName(region.getName());
        //查询楼盘名称


        //查询经纪人电话
        Broker broker = brokerMapper.selectBrokerById(shopInsertReqDTO.getBrokerId());
        //设置经纪人电话
        houses.setBrokerTel(broker.getMobile());
        // 获取当前登陆人
        Long userId = SecurityUtils.getUserId();
        houses.setCreateBy(String.valueOf(userId));
        //无小区
        houses.setCommunityId(0L);
        houses.setCommunityName("暂无");
        //房源类型
        houses.setHouseType(HouseType.MERCANTILE_OCCUPANCY.getTypeId());
        //添加房屋
        housesMapper.insertHouses(houses);
        //赋值商铺属性
        OfficeBuilding officeBuilding = new OfficeBuilding();
        BeanUtil.copyProperties(shopInsertReqDTO, officeBuilding);
        //房源id和商铺id是同一个
        officeBuilding.setId(houseId);
        //计算单价 销售价格除以面积

        BigDecimal divide = officeBuilding.getSellingPrice().divide(new BigDecimal(shopInsertReqDTO.getTotalArea()), 2, RoundingMode.HALF_DOWN);
        officeBuilding.setUnitPrice(divide);
        //添加商铺
        baseMapper.insert(officeBuilding);

        //添加商铺特色中间表
        ArrayList<ShopCharacteristics> shopCharacteristics = new ArrayList<>();
        for (Integer characteristic : shopInsertReqDTO.getCharacteristics()) {
            shopCharacteristics.add(new ShopCharacteristics(null, characteristic, houseId));
        }
        shopCharacteristicsService.saveBatch(shopCharacteristics);
        //添加商铺特色0
        ArrayList<ShopFacilities> shopFacilities = new ArrayList<>();
        for (Integer facilitiesId : shopInsertReqDTO.getFacilitiesIds()) {
            shopFacilities.add(new ShopFacilities(null, houseId, facilitiesId));
        }
        shopFacilitiesService.saveBatch(shopFacilities);
        //添加图片
        shopInsertReqDTO.getImageList().stream().forEach(item -> {
            item.setHouseInformationId(houseId);
        });
        imageService.saveBatch(shopInsertReqDTO.getImageList());

        return R.ok();
    }

    @Override
    public List<HouseListRespDTO> officeList(HouseQueryReqDTO houseQueryReqDTO) {
        List<HouseListRespDTO> houseListRespDTOS = housesMapper.selectHouseInfo(HouseType.MERCANTILE_OCCUPANCY.getTypeId(),houseQueryReqDTO.getName());
        return houseListRespDTOS;
    }

    @Override
    @Transactional//开启事务
    public int delById(String id) {
        Long aLong = Long.valueOf(id);
        //查询当前房源是否存在
        Houses houses = housesMapper.selectHousesById(aLong);
        if (Objects.isNull(houses)) {
            return 0;
        }
        //删除图片表
        imageService.removeById(aLong);
        //删除设施中间表
        QueryWrapper<ShopFacilities> shopFacilitiesQueryWrapper = new QueryWrapper<>();
        shopFacilitiesQueryWrapper.lambda().eq(ShopFacilities::getOfficeBuildingId,aLong);
        shopFacilitiesService.remove(shopFacilitiesQueryWrapper);
        //删除特色中间表
        QueryWrapper<ShopCharacteristics> shopCharacteristicsQueryWrapper = new QueryWrapper<>();
        shopCharacteristicsQueryWrapper.lambda().eq(ShopCharacteristics::getOfficeBuildingId, aLong);
        shopCharacteristicsService.remove(shopCharacteristicsQueryWrapper);
        //删除商业用房表
        baseMapper.deleteById(aLong);
        //删除房源信息表
        housesMapper.deleteHousesById(aLong);
        return 1;
    }
}




